package db

import (
	stdlog "log"
	"os"
	"time"

	_ "github.com/mattn/go-sqlite3"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var dbop *gorm.DB

// NewDB 连接新的数据库，不使用默认的
func NewDB(path string, showSQL bool) (op *gorm.DB, err error) {
	gConfig := gorm.Config{
		QueryFields: true,
	}
	if showSQL {
		newLogger := logger.New(
			stdlog.New(os.Stdout, "\r\n", stdlog.LstdFlags), // io writer
			logger.Config{
				SlowThreshold: time.Second, // 慢 SQL 阈值
				LogLevel:      logger.Info, // Log level
				Colorful:      true,        // 禁用彩色打印
			},
		)
		gConfig.Logger = newLogger
	}
	op, err = gorm.Open(sqlite.Open(path), &gConfig)
	return
}

// SetGlobalHandler 设置全局句柄
func SetGlobalHandler(op *gorm.DB) {
	dbop = op
}

// New 获取数据库操作对象
func New() *gorm.DB {
	return dbop
}
